package AreaService

import (
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/app/response/CommonResp"
	"gdshop-admin-go-api/library/response"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/net/ghttp"
	"strings"
)

func Tree(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	level := r.GetInt("level", 1)
	if level < 1 || level > 4 {
		return response.FailByRequestMessage(nil, "level 取值1-4")
	}
	var areaList []*CommonResp.AreaTree
	err := toolsDb.GetUnSafaTable(ctx, "area_plus").Fields("code,name").
		Where("is_show = 1 AND LENGTH(`code`) <= ?", level*2).Structs(&areaList)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	var fanhui []*CommonResp.AreaTree
	for _, item := range areaList {
		if len(item.Code) != 2 {
			continue
		}
		item.Childrens = makeTree(areaList, item)

		fanhui = append(fanhui, item)
	}
	return response.SuccessByRequestMessageData(nil, "成功", fanhui)
}

func makeTree(data []*CommonResp.AreaTree, node *CommonResp.AreaTree) []*CommonResp.AreaTree {
	tmpList := []*CommonResp.AreaTree{}
	codeLen := len(node.Code) + 2
	for _, item := range data {
		if len(item.Code) != codeLen {
			continue
		}

		if strings.Compare(item.Code, "不显示") == 0 {
			continue
		}

		if strings.Index(item.Code, node.Code) != 0 {
			continue
		}

		item.Childrens = makeTree(data, item)

		tmpList = append(tmpList, item)
	}

	return tmpList
}

func List(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	parentCode := r.GetString("parent_code", "")
	codeLen := len(parentCode) + 2
	var areaList []*CommonResp.AreaTree
	err := toolsDb.GetUnSafaTable(ctx, "area_plus").Fields("code,name").
		Where("is_show = 1 AND LENGTH(`code`) = ? AND `code` LIKE ?", codeLen, parentCode+"%").Structs(&areaList)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	return response.SuccessByRequestMessageData(nil, "成功", areaList)
}

func LevelList(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	level := r.GetInt("level", 1)
	if level < 1 || level > 4 {
		return response.FailByRequestMessage(nil, "level 取值1-4")
	}
	var areaList []*CommonResp.AreaTree
	err := toolsDb.GetUnSafaTable(ctx, "area_plus").Fields("code,name").
		Where("is_show = 1 AND LENGTH(`code`) = ?", level*2).Structs(&areaList)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	return response.SuccessByRequestMessageData(nil, "成功", areaList)
}
